package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.SupplierBean;
import com.project.mapper.ISupplierMapper;
import com.project.service.ISupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class SupplierServiceImpl implements ISupplierService {
    @Autowired
    private ISupplierMapper supplierMapper;

    @Override
    public List<SupplierBean> findAll() {//查询所有供应商返回供应商集合
        QueryWrapper<SupplierBean> qw = new QueryWrapper<>();
        return supplierMapper.selectList(qw);
    }

    @Override
    public IPage<SupplierBean> findByItem(Integer pageNO, String name, String scope) {//根据输入的供应商名称，经营的范围动态查询，返回供应商分页对象
        QueryWrapper<SupplierBean> qw = new QueryWrapper<>();
        if (name != null && name.length() != 0) {
            qw.like("su_name", name);
        }
        if (scope != null && scope.length() != 0) {
            qw.like("su_scope", scope);
        }
        return supplierMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    @Override
    public SupplierBean findById(Integer id) {//按照供应商id查询供应商信息
        return supplierMapper.selectById(id);
    }

    @Override
    public void updateInfo(Integer id, String director, String phone) {//根据供应商id修改供应商负责人名字和电话号码
        SupplierBean supplier = supplierMapper.selectById(id);
        supplier.setDirector(director);
        supplier.setDirectorPhone(phone);
        supplierMapper.updateById(supplier);
    }

    @Override
    public boolean add(SupplierBean supplierBean) {//添加供应商，* 如果供应商已存在，则不允许添加。
        QueryWrapper<SupplierBean> qw = new QueryWrapper<>();
        String name=supplierBean.getName();
        qw.eq("su_name",name);
        SupplierBean supplier = supplierMapper.selectOne(qw);
        if (supplier == null) {
            supplierMapper.insert(supplierBean);
            return true;
        }
        return false;
    }

    @Override
    public void addExcel(List<SupplierBean> list) {
        QueryWrapper<SupplierBean> queryWrapper = new QueryWrapper<>();
        for (SupplierBean Item : list ) {
            queryWrapper.eq("su_name",Item.getName());
            SupplierBean supplierObj = supplierMapper.selectOne(queryWrapper);
            if(supplierObj == null){
                supplierMapper.insert(Item);
            }
        }
    }
}
